//
// Created by postgres on 7/30/17.
//
#include <stdio.h>

# include <stdlib.h>
#include "../include/09sort/files.h"
#include "../include/09sort/merge_sort.h"
void write_file_for_merge1(Datatype a[],int size,int every_lie,int fileid){
    FILE *fp;
    char file_id[15];
    char directory[12];
    char meg[4]=merge_name;
    char dir[2]="/";
    char dest[200]=merge1_path;
    sprintf(file_id,"%d",fileid);   //int to char
    sprintf(directory,"%d",every_lie);
    //printf("%s",dest);
    strcat (dest,directory);
    strcat (dest,dir);
    int result=mkdir(dest,0777);
    strcat (dest,meg);
    strcat (dest,file_id);
    fp = fopen(dest, "w");
    int i;
    for(i=0;i<size;i++){
        fprintf (fp, "id:%d\n", a[i]);
    }
    fclose(fp);
}

void get_filename(char dest[],int size,int every_lie,int fileid){
    int i;
    for(i=0;i<size;i++)
        dest[i]='\000';
    char file_id[15]={'\000'};
    char directory[12]={'\000'};
    char meg[5]={'\000'};
    char dir[2]="/";
    strcat (meg,merge_name);
    strcat (dest,merge1_path);
    sprintf(file_id,"%d",fileid);   //int to char
    sprintf(directory,"%d",every_lie);
    strcat (dest,directory);
    strcat (dest,dir);
    int result=mkdir(dest,0777);
    strcat (dest,meg);
    strcat (dest,file_id);
}
void order_bubble(Datatype a[],int size){
    int i, j;
    Datatype temp;
    //冒泡法排序实现从小到大排序
    for( i=0;i<size;i++) //进行10次循环
    {
        for( j=i+1;j<size;j++) //循环比较剩余的变量
        {
            if(a[i] > a[j]) //如果前面一个数比后面数大，交换两个数的值
            {
                temp = a[i];
                a[i] = a[j];
                a[j] = temp;
            }
        }
    }
}


int main_files_test ()
{
    Datatype arr[memory_nums];
    FILE *fp;
    fp = fopen(sort_init, "r+");
    int len = 0, i = 0,m=0;
    while (len != EOF) {
        // \tab is separator
        len = fscanf(fp, "id:%d ", &arr[i]);
        if(i==(memory_nums-1)&&len != EOF){
            order_bubble(arr,memory_nums);
            write_file_for_merge1(arr,memory_nums,1,m++);
            i=-1; //clear

        }
        i++;
    }
    fclose(fp);
    //loser_tree_main(m);
    return 0;
}

